package com.by.cart.listener;

import com.by.cart.service.CartService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.connection.Message;
import org.springframework.data.redis.listener.KeyExpirationEventMessageListener;
import org.springframework.data.redis.listener.RedisMessageListenerContainer;
import org.springframework.stereotype.Component;


@Component
public class RedisListener extends KeyExpirationEventMessageListener {

    private static final String CART_PREFIX = "cart:";

    @Autowired
    private CartService cartService;

    public RedisListener(RedisMessageListenerContainer listenerContainer) {
        super(listenerContainer);
    }


    @Override
    public void onMessage(Message message, byte[] pattern) {
        String expiredKey = message.toString();

        // 判断过期的键是否是购物车的键
        if (expiredKey.startsWith(CART_PREFIX)) {
            try {
                // 提取用户ID
                String userIdStr = expiredKey.substring(CART_PREFIX.length());
                Long userId = Long.valueOf(userIdStr);

                //将购物车数据持久化到数据库
               cartService.persistToDatabase(userId);
            } catch (Exception e) {
                // 处理异常，例如记录日志
                e.printStackTrace();
            }
        }
    }
}
